package com.stu.controller;

import com.stu.commons.ServerResponse;
import com.stu.pojo.Flow;
import com.stu.pojo.Myorder;
import com.stu.service.IFlowService;
import com.stu.service.IMyorderService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.UUID;

@RestController
@RequestMapping("/flow")
public class FlowController {

    @Autowired
    private IFlowService flowService;

    @Autowired
    private IMyorderService myorderService;

    /**
     * 创建支付流水
     * @param traceNo 订单号
     * @param totalAmount 支付金额
     * @return 返回流水信息
     */
    @GetMapping("/getFlow")
    public ServerResponse getFlow(@RequestParam("traceNo") String traceNo,
                                  @RequestParam("totalAmount") Double totalAmount) {
        Myorder myorder = myorderService.selectByOrderNumber(traceNo);
        if (myorder == null) {
            return ServerResponse.fail("订单不存在", null);
        }

        Flow flow = new Flow();
        flow.setFlowNumber(UUID.randomUUID().toString());
        flow.setMyorderId(myorder.getMyorderId());
        flow.setFlowPayPrice(totalAmount);
        flow.setFlowPayTime(LocalDate.now().toString());
        flow.setFlowPayMethod("支付宝");
        flow.setFlowStatus(0);

        flowService.save(flow);

        return ServerResponse.success("支付流水创建成功", flow);
    }

    /**
     * 查询支付流水
     * @param traceNo 订单号
     * @return 返回流水信息
     */
    @GetMapping("/notifySaveFlow")
    public ServerResponse notifySaveFlow(@RequestParam("traceNo") String traceNo) {
        ServerResponse response = flowService.getFlow(traceNo);
        if (response.getData() == null) {
            return ServerResponse.fail("未找到支付流水", null);
        }
        return ServerResponse.success("查询成功", response.getData());
    }
}
